package newui.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.TrainActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.GameWebActivity;
import com.shwread.android.qysw.activity.NewBookDetailActivity;
import com.shwread.android.qysw.activity.SearchThemeActivity;
import com.shwread.android.qysw.activity.TrainExamCommonWebActivity;
import com.shwread.android.qysw10000241.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.page.NewTrainingExamPage;
import com.shwread.android.ui.widget.TrainExamContentView1;
import com.shwread.android.ui.widget.TrainExamModelView;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.bean.BannerInfo;
import logic.bean.BookInfo;
import logic.bean.TrainIndexBean;
import logic.bean.TrainIndexModel;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;

/**
 * Created by lex on 2017/7/26.
 */

public class CourseActivity extends BaseBusinessActivity implements View.OnClickListener,
        TrainExamModelView.OnModuleSelectedListener {


    private static String              Tag         = "TrainExam";
    private boolean                    isLastSuccess;
    private LinearLayout contentLinearLayout;
    private PullToRefreshScrollView contentView;
    //加载动画
    private View                       loadingView;
    private ImageView loadingImg, gotoTopImg;
    private AnimationDrawable animationDrawable;
    //顶部菜单
    private TextView tvTitle;
    private Button btnBack, btnSearch;
    private ImageView                  ivPersion;

    //banner
    private HashMap<Integer, View> views;
    private QYViewPager vpPager;
    private ViewGroup vgPoints;
    private List<BannerInfo> banners;
    private ViewPagerAdapter pagerAdapter;
    private static Rect ViewPagerRect;
    //模块
    TrainExamModelView modelView;
    //模块内容
    TrainExamContentView1 examContent;
    private static NewTrainingExamPage instance;
    private int                        currentType = -1;
    public static boolean              updateData = false;
    private Handler handler = new Handler();
    
    @Override
    public Handler getUIHandler() {
        return handler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_trainingexam_lay);
        initView();
        setListener();
        QyreaderPerferencesUtil.getInstance(this, Const.phone_number).setTrainIndexCid("");
        TrainActionHelp.qryTrainIndexForClient(this, "y", new GetTrainIndexAction());
        if (NetworkUtil.isNetAvailable(CourseActivity.this))
        {
            //			if (!isLastSuccess) updateLoadingView(0);
            if (currentType == -1)
            {
                contentView.getRefreshableView().scrollTo(0, 0);
            }
            gotoTop();
        }
        else
        {
            new NoNetDialog(CourseActivity.this).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != banners) {
            banners.clear();
        }
        if (null != vpPager && null != action) {
            vpPager.removeCallbacks(action);
        }
    }

    void initView() {
        contentView = (PullToRefreshScrollView) findViewById(R.id.new_trainexam_view);
        PullToRefreshUtil.initLabel(CourseActivity.this, contentView);
        contentLinearLayout = (LinearLayout) findViewById(R.id.ll_newtrainexam_contentview);
        //加载动画
        loadingView = findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);
        updateLoadingView(0);
        //顶部菜单
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("课程");
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        ivPersion = (ImageView) findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.GONE);
        btnSearch = (Button) findViewById(R.id.common_header_search);
        btnSearch.setVisibility(View.VISIBLE);
        //banner
        banners = new ArrayList<BannerInfo>();
        views = new HashMap<Integer, View>();
        vpPager = (QYViewPager) findViewById(R.id.enterprise_head_pager);
        vgPoints = (ViewGroup) findViewById(R.id.enterprise_head_points);
        // 获取ViewPager在屏幕的位置
        final ViewTreeObserver observer = vpPager.getViewTreeObserver();
        ViewTreeObserver.OnGlobalLayoutListener global = new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout() {
                if (ViewPagerRect == null)
                {
                    ViewPagerRect = new Rect();
                    vpPager.getGlobalVisibleRect(ViewPagerRect);
                }
            }
        };
        observer.addOnGlobalLayoutListener(global);

        //模块
        modelView = new TrainExamModelView(CourseActivity.this, new ArrayList<TrainIndexModel>());
        //模块内容
        examContent = new TrainExamContentView1(CourseActivity.this);
        examContent.setActivity(CourseActivity.this);
        examContent.setTrainExamContentViewListener(new TrainExamContentView1.TrainExamContentViewListener()
        {

            @Override
            public void OnLoadDataCompleted(int flag) {
                modelView.setCanSwitchModule(true);
                if (flag == 1)
                { //首次装载
                    contentView.scrollTo(0, 0);
                    contentView.getRefreshableView().scrollTo(0, 0);
                    contentView.onRefreshComplete();
                }
                else if (flag == 2)
                {//装载更多
                    contentView.onRefreshComplete();
                }
            }
        });

    }

    void setListener() {
        //		btnBack.setOnClickListener(this);
        ivPersion.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        vpPager.setOnPageChangeListener(new PagerChangeListener());
        pagerAdapter = new ViewPagerAdapter(CourseActivity.this, views, new BannerClick());
        vpPager.setAdapter(pagerAdapter);
        contentView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>()
        {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown())
                { //下拉刷新
                    modelView.setCanSwitchModule(false);
                    refresh();
                }
                else if (contentView.isFooterShown())
                { //上拉加载
                    loadMore();
                }
            }
        });
    }

    //下拉刷新
    private void refresh() {
        if (currentType != -1)
        {
            examContent.showModelData(currentType, 2);
        }
        else
        {
            modelView.setCanSwitchModule(true);
            contentView.onRefreshComplete();
        }
    }

    //上拉加载更多
    private void loadMore() {

        if (examContent.getDataSize() == 0)
        {
            PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
        }
        else
        {
            if (examContent.getHasMore())
            {
                //加载下一页
                examContent.getNextPage();
                return;
            }
            else
            {
                //没有更多了， 所以不再加载下一页
                PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
            }
        }
        contentView.onRefreshComplete();

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
               finish();
                break;
//            case R.id.common_header_persion:
//                bActivity.goPersonalActivity();
//                break;
            case R.id.common_header_search:
                Intent intent = new Intent(CourseActivity.this, SearchThemeActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /*************************** 首页相关start ********************************************************/
    //	private QryTrainIndexForClientAction trainIndexAction;

    private class GetTrainIndexAction
            extends
            ObjectHttpResponseHandler<TrainIndexBean>
    {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            LogUtil.d(Tag, responseString);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, final TrainIndexBean object, String responseString) {
            CourseActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    QyreaderPerferencesUtil.getInstance(CourseActivity.this, Const.phone_number).setTrainIndexCid(object.cid);
                    modelView = new TrainExamModelView(CourseActivity.this, object.moduleList);
                    modelView.setOnModuleSelectedListener(CourseActivity.this);
                    // 传模块数据
                    examContent.setModuleList(object.moduleList);
                    modelView.setBaseActivity(CourseActivity.this);
                    modelView.setCanSwitchModule(true);
                    // 重新加载第一个模块
                    examContent.showModelData(1, 1);
                    contentLinearLayout.addView(modelView);
                    contentLinearLayout.addView(examContent);
                    TrainActionHelp.qryTrainIndexBanner(CourseActivity.this, object.cid, new GetBannerAction());

                }
            });

        }

        @Override
        public Type getType() {
            return new TypeToken<TrainIndexBean>()
            {
            }.getType();
        }

    }

    /*************************** 首页相关end ********************************************************/
    /****************************** banner相关start ***********************************************/
    //获取banner action
    //	private QryTrainIndexBannerAction bannerAction;

    /** 获取企业专区Banner数据 */
    private class GetBannerAction
            extends
            ObjectHttpResponseHandler<List<BannerInfo>>
    {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            
            CourseActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateLoadingView(-1);
                }
            });
            isLastSuccess = false;

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<BannerInfo> object, String responseString) {

            banners.clear();
            if (object.size() <= 1)
            {
                banners = object;
            }
            else
            {
                banners.add(object.get(object.size() - 1));
                banners.addAll(object);
                banners.add(object.get(0));
            }
            System.out.println("企业专区banner obj:" + banners.toString());
            CourseActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (banners.size() > 0)
                    {
                        pagerAdapter.setData(banners);
                        initBannerView();
                    }
                    updateLoadingView(1);
                    gotoTop();
                }
            });
        }

        @Override
        public Type getType() {
            return new TypeToken<List<BannerInfo>>()
            {
            }.getType();
        }
    }

    /** 回到顶部 */
    private void gotoTop() {
        examContent.post(new Runnable()
        {
            @Override
            public void run() {
                contentView.getRefreshableView().scrollTo(0, 0);
            }
        });
    }

    void initBannerView() {
        if (banners.size() == 0) return;
        vgPoints.removeAllViews();
        for (int i = 0; i < banners.size() - 2; i++)
        {
            View view = this.getLayoutInflater().inflate(R.layout.banner_grid_item, null);
            vgPoints.addView(view);
        }
        vpPager.setCurrentItem(1);
        setViewPoint();
        pagerAdapter.notifyDataSetChanged();
        startScroll();
    }

    private class PagerChangeListener
            implements
            ViewPager.OnPageChangeListener
    {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int i) {
            int pageIndex = i;
            if (i == 0)
            {
                // 当视图在第一个时，将页面号设置为图片的最后一张。  
                pageIndex = banners.size() - 2;
            }
            else if (i == banners.size() - 1)
            {
                // 当视图在最后一个是,将页面号设置为图片的第一张。  
                pageIndex = 1;
            }
            if (i != pageIndex)
            {
                vpPager.setCurrentItem(pageIndex, false);
            }
            setViewPoint();
            startScroll();
        }
    }

    Runnable action = new Runnable()
    {
        @Override
        public void run() {
            int currentItem = vpPager.getCurrentItem();
            currentItem++;
            if (currentItem >= pagerAdapter.getCount())
            {
                currentItem = 0;
            }
            vpPager.setCurrentItem(currentItem);
        }
    };

    private void startScroll() {
        if (banners.size() <= 1) return;
        vpPager.removeCallbacks(action);
        vpPager.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);
    }

    private void setViewPoint() {
        for (int i = 0; i < vgPoints.getChildCount(); i++)
        {
            View view = vgPoints.getChildAt(i);
            ImageView img = (ImageView) view.findViewById(R.id.banner_grid_item_image);

            if (i == vpPager.getCurrentItem() - 1)
            {
                img.setBackgroundResource(R.drawable.banner_grid_cur);
            }
            else
            {
                img.setBackgroundResource(R.drawable.banner_grid);
            }
        }
    }

    private class BannerClick
            implements
            BannerOnClickListener
    {
        @Override
        public void click(BannerInfo info) {
            clickBanner(info);
        }
    }

    // TODO 点击Banner
    private void clickBanner(BannerInfo info) {
        switch (info.getType()) {
            case BannerInfo.TYPE_BANNER:

                break;
            case BannerInfo.TYPE_BOOKS:

                break;
            case BannerInfo.TYPE_BOOKSURL:
                CourseActivity.this.goBookDetailActivity(info.getBooks());
                break;
            case BannerInfo.TYPE_URL:
                //isTrain为1代表是培训的banner 
                if (info.getIsTrain() == 1)
                {
                    String cid = QyreaderPerferencesUtil.getInstance(CourseActivity.this, Const.phone_number).getTrainIndexCid();
                    Intent intent = new Intent(CourseActivity.this, TrainExamCommonWebActivity.class);
                    intent.putExtra(DefaultConsts.title_s, " 详情");
                    intent.putExtra(DefaultConsts.req_url_s, TrainActionHelp.getUrl() + info.getContent() + "?trainId=" + info.getTrainId() + "&cid=" + cid);
                    startActivity(intent);
                }
                else goWebViewActivity(info);
                break;
        }
    }

    public void goWebViewActivity(BannerInfo info) {
        Intent webIntent = new Intent(this, GameWebActivity.class);
        webIntent.putExtra(DefaultConsts.title_s, info.getBannerName());
        webIntent.putExtra(DefaultConsts.req_url_s, info.getContent());
        webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(webIntent);
    }

    public void goBookDetailActivity(List<BookInfo> list) {
        if (list != null && list.get(0) != null) {
            // #ifdef SHOW_OLDBOOKDETAIL
            // $ Intent bookIntent = new Intent(this, BookDetailActivity.class);
            // #else
            Intent bookIntent = new Intent(this, NewBookDetailActivity.class);
            // #endif

            bookIntent.putExtra("BookInfo", list.get(0));
            startActivity(bookIntent);
        } else {
            Util.showToast(this, "书籍已下架");
        }
    }

    /****************************** banner相关end ****************************************************/
    /**
     * 首次进入page加载动画
     *
     * @param flag
     *            0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning())
                {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                contentView.setVisibility(View.VISIBLE);
                break;
        }
    }

    //模块选中
    @Override
    public void moduleSelected(TrainIndexModel model) {
        //		PullToRefreshUtil.initLabel(context, contentView);
        contentView.getRefreshableView().scrollTo(0, 0);
        PullToRefreshUtil.initLabel(CourseActivity.this, contentView);
        currentType = model.type;
        examContent.showModelData(model.getType(), 1);
        // 在线考试去掉上拉加载
        if (model.type == 3) {
            contentView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            contentView.setMode(PullToRefreshBase.Mode.BOTH);
        }
    }

    @Override
    public void onError(String error) {

    }
}
